﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using ClassLibrary.DAO;
using ClassLibrary.Data;
using System.Globalization;
using System.IO;

public partial class UserControl_ucAddProduct : System.Web.UI.UserControl
{
    TblProductsDAO ProductsDAO = new TblProductsDAO(Global.CONNECTION_STRING);
    TblPhoneBranDAO phoneBrandDAO = new TblPhoneBranDAO(Global.CONNECTION_STRING);
    TblModelDAO modelDAO = new TblModelDAO(Global.CONNECTION_STRING);
    TblJobsDAO JobsDAO = new TblJobsDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        string idProd = Request.QueryString["idProd"];
        if (!IsPostBack)
        {
            if (idProd == String.Empty || idProd == "")
            {
                LoadModel();
                LoadBrandPhone();
                
               // LoadImgItemByID();
            }
            else
            {
                LoadProductByID();
                LoadModel();
                LoadBrandPhone();
                LoadImgItemByID();
            }
        }
    }

    private void LoadProductByID()
    {
        string idProd = Request.QueryString["idProd"];
        DataTable productDT = ProductsDAO.GetProductById(Convert.ToInt32(idProd));
        foreach (DataRow dr in productDT.Rows)
        {
            txtProductID.Text = dr["ProductID"].ToString();
            txtProductName.Text = dr["ProductName"].ToString();
            txtProductCode.Text = dr["productCode"].ToString();
            drModel.SelectedValue = dr["IDmodel"].ToString();
            drManufacture.SelectedValue = dr["IDPhoneBrand"].ToString();
            txtType.Text = dr["ProductType"].ToString();
            txtDes.Text = dr["ProductDescription"].ToString(); 
            txtCost.Text = dr["Cost"].ToString();
            txtRRP.Text = dr["RRP"].ToString();
            txtQuantity.Text = dr["QuantityOnHand"].ToString();
        }
    }

    private void LoadImgItemByID()
    {
        string id = Request.QueryString["idProd"];
        grdImgItems.DataSource = ProductsDAO.GetImgItems(Convert.ToInt32(id));
        grdImgItems.DataBind();
    }
    private void LoadModel()
    {
        //DataTable dt = modelDAO.GetModelByIdBrand(Convert.ToInt32(drBrand.SelectedValue));
        drModel.DataSource = modelDAO.GetModel();
        drModel.DataTextField = "Model";
        drModel.DataValueField = "IDModel";
        drModel.DataBind();
        ListItem lstItem = new ListItem("-Select-", "");
        drModel.Items.Insert(0, lstItem);

    }

    private void LoadBrandPhone()
    {
        drManufacture.DataSource = JobsDAO.LoadBrandPhone();

        drManufacture.DataTextField = "BrandName";
        drManufacture.DataValueField = "IDBrand";
        drManufacture.DataBind();
        ListItem lstItem = new ListItem("-Select-", "");
        drManufacture.Items.Insert(0, lstItem);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool flag = false;
        //string idPro = Request.QueryString["idProd"].ToString();
        if (Session[Global.SESSION_LOGGED_USER] == null)
        {
            Response.Redirect("~/Login.aspx");
            return;
        }
        else
        {
            try
            {
                TblProducts product = new TblProducts();
                product.ProductName = txtProductName.Text;
                product.ProductCode = txtProductCode.Text;
                product.IDPhoneBrand=Convert.ToInt32( drManufacture.SelectedValue);
                product.IDModel = Convert.ToInt32(drModel.SelectedValue);
                product.ProductType = txtType.Text;
                product.ProductDescription = txtDes.Text;
                product.Cost = Convert.ToDecimal(txtCost.Text);
                product.RRP = Convert.ToDecimal(txtRRP.Text);
                product.QuantityOnHand = Convert.ToInt32(txtQuantity.Text);
                product.Type = Convert.ToInt32((drType.SelectedValue));

               if (txtProductID.Text == "")
               {
                   product.ProductID = 0;
                   ProductsDAO.InsUpdProducts(product, 1);
               }
               else
               {
                   product.ProductID = Convert.ToInt32(txtProductID.Text);
                   ProductsDAO.InsUpdProducts(product, 2);
               }

               flag = true;
            }
            catch (Exception ex)
            {
                Session[Global.SESSION_ERROR] = ex;
                Response.Redirect(Global.ERROR_PAGE);
            }
            if(flag)
                
                    Response.Redirect("~/Admin/ListProducts.aspx");
               
        }
    }
    protected void drManufacture_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable dt = modelDAO.GetModelByIdBrand(Convert.ToInt32(drManufacture.SelectedValue));
        foreach (DataRow dr in dt.Rows)
        {
            drModel.DataSource = dt;
            drModel.DataTextField = "Model";
            drModel.DataValueField = "IDModel";
            drModel.DataBind();
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/AddNewProduct.aspx");
    }
    protected void btnModelDelete_Click(object sender, ImageClickEventArgs e)
    {
        // string id = Request.QueryString["id"];
        bool flag = false;
        try
        {

            TblModel model = new TblModel();
            model.IDModel = Convert.ToInt32(((ImageButton)sender).CommandArgument);
            int IDDelete = Convert.ToInt32(((ImageButton)sender).CommandArgument);
            //DataTable dt = modelDAO.ge

            ProductsDAO.DeleteProduct(IDDelete);
            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE_ADMIN);
        }
        if (flag)
        {
            Response.Redirect("~/Admin/AddNewProduct.aspx");
        }
    }
    protected void txtProductName_TextChanged(object sender, EventArgs e)
    {
        txtProductName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtProductName.Text);
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string id = Request.QueryString["idProd"];
        bool flag = false;
        try
        {

            string path = Server.MapPath("~\\Admin\\image\\Items\\");
            string filename = id + "_" + fileUpload.FileName;

            TblProductImage productImg = new TblProductImage();
            // lblMessage.Text = path;
            if (File.Exists(path + "\\" + filename))
            {
                lblMessage.Text = "The image file already exist. Please choose other file or change the file name to upload";
                return;
            }
            fileUpload.SaveAs(path + "\\" + filename);
            productImg.ImageURL = filename;
            productImg.ProductID = Convert.ToInt32(id);

            ProductsDAO.InsImageItem(productImg, 1);
            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE_ADMIN);
        }
        if (flag)
        {
            if (id == null || id == "")
                Response.Redirect("~/Admin/AddNewProduct.aspx?idProd=" + id);
            else
                Response.Redirect("~/Admin/AddNewProduct.aspx?idProd=" + id);
        }
    }

    protected void btnDelImg_Click(object sender, ImageClickEventArgs e)
    {
        string id = Request.QueryString["idProd"];
        bool flag = false;
        try
        {
            TblProductImage ProductImg = new TblProductImage();

            ProductImg.ID = Convert.ToInt32(((ImageButton)sender).CommandArgument);
            int idXoa = Convert.ToInt32(((ImageButton)sender).CommandArgument);
            ProductImg = ProductsDAO.GetItemImageByID(Global.ConvertToInt(id), idXoa);
            ProductsDAO.DeleteImgItem(ProductImg);
            string filename = ProductImg.ImageURL;
            if (File.Exists(Server.MapPath("~\\Admin\\image\\Items\\" + filename)))
            {
                File.Delete(Server.MapPath("~\\Admin\\image\\Items\\" + filename));
            }

            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE_ADMIN);
        }
        if (flag)
        {
            LoadImgItemByID();
        }

    }
    protected void grdImgItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (DataControlFieldCell cell in e.Row.Cells)
            {
                // check all cells in one row
                foreach (Control control in cell.Controls)
                {
                    ImageButton button = control as ImageButton;
                    if (button != null && button.CommandName == "Delete")
                    {
                        // Add delete confirmation
                        button.CommandArgument = ((TblProductImage)e.Row.DataItem).ID.ToString();
                        button.OnClientClick = "if (!confirm('Are you sure to delete this Gallery?')) return false;";
                    }
                }
            }
        }
    }
}
